/**
 * @description ETF
 * @author wangjianjun
 */

import React, { PureComponent } from 'react';
import { TableC, CollectC, TabC, ExportC } from '../../../../comps';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Tooltip } from 'antd';
import { connect } from 'dva';
import SetColumns from '../common/SetColumns';
import _ from 'lodash';
import { isZiGuanEvir } from '../../../../utils/commonFunc';
import config from '../../../../comps/business/tradingMarket/config';

@Form.create()
@connect(({ positionInquiryM, loading }) => ({
  positionInquiryM,
  loading,
}))
export default class Etf extends PureComponent {
  constructor(props) {
    super(props);
    this.scrollx = 0;
    this.newColumns = [];
    this.state = {
      search: {},
      columns: [],
      dataSource: [],
      page: 1,
      pageSize: 20,
      total: 0,
      account: {},
      treeData: [],
      checkedKeys: [],
      scrollx: 0,
      isZiGuan: false,
      tabType: 'pt',
    };
  }

  componentDidMount() {
    const { dispatch, etfArgs } = this.props;
    // etf查表头信息
    dispatch({
      type: 'positionInquiryM/queryShowCol',
      payload: {
        type: 'Trade_Ana_Fnd_Hold_Info_ETF',
      },
      callback: (data) => {},
    });
    const temp = isZiGuanEvir();
    const isZiGuan = !!temp; // 判断该页面是在资管被引入的，还是maat
    this.setState({ isZiGuan });
    this.setState(
      {
        search: etfArgs,
      },
      () => {
        this.getTableData();
      },
    );
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const init = !this.props.etfArgs ? '' : JSON.stringify(this.props.etfArgs);
    const initN = !nextProps.etfArgs ? '' : JSON.stringify(nextProps.etfArgs);

    if (init != initN) {
      this.setState(
        {
          search: nextProps.etfArgs,
        },
        () => {
          this.getTableData();
        },
      );
    }
  }

  // 分页切换
  handleTableChange = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    this.setState(
      {
        page: current,
        pageSize,
      },
      () => {
        this.getTableData('pageChange');
      },
    );
  };

  // 查询表格数据

  getTableData = (type) => {
    const { dispatch } = this.props;
    const { page, pageSize, search, tabType } = this.state;
    const params = {};
    params.pageSize = pageSize;
    if (type != 'pageChange') {
      // 点击查询按钮 重置页码
      this.setState({
        page: 1,
      });
      params.page = 1;
    } else {
      // 点击页码切换时候调用
      params.page = page;
    }
    // 列表数据
    dispatch({
      type: 'positionInquiryM/etfTable',
      payload: {
        ...params,
        ...search,
        isETF: '0',
        searchType: tabType,
      },
      callback: (res) => {
        res.data &&
          res.data.map((item, key) => {
            item.key = key;
          });
        this.setState({
          dataSource: res.data,
          total: res.total,
        });
      },
    });

    if (type != 'pageChange') {
      // 获取统计信息
      dispatch({
        type: 'positionInquiryM/getSearchTotal',
        payload: {
          ...search,
          type: '11',
        },
        callback: (data) => {
          this.setState({
            account: data,
          });
        },
      });
    }
  };

  rightButton = () => {
    const { search, tabType } = this.state;
    const {
      positionInquiryM: { checkedKeysInfo },
    } = this.props;

    return (
      <div>
        <div style={{ display: 'inline-block' }}>
          <ExportC style={{ marginTop: '10px' }} url='api/v1/tradeAnaFndHoldInfo/exportFnd' search={this.changeSearch('0', tabType)} />
        </div>
        <div style={{ display: 'inline-block', marginLeft: '5px' }}>
          <SetColumns type={tabType == 'pt' ? '31' : '32'} parameter='Trade_Ana_Fnd_Hold_Info_ETF' checkedKeysInfo={checkedKeysInfo} />
        </div>
      </div>
    );
  };

  // 导出参数调整
  changeSearch(isETF, searchType) {
    const { search } = this.state;
    const newSearch = _.cloneDeep(search);
    if (newSearch && newSearch.fundId) {
      newSearch.fundId = newSearch.fundId.join(',');
    }
    if (isETF == '1' || isETF == '0') {
      newSearch.isETF = isETF;
    }
    if (searchType == 'pt' || searchType == 'fz') {
      newSearch.searchType = searchType;
    }
    return newSearch;
  }

  render() {
    const {
      positionInquiryM: { columnsInfo },
      loading,
    } = this.props;
    const { account, tabType } = this.state;
    const columns = tabType == 'pt' ? _.cloneDeep(columnsInfo[31].columns) : _.cloneDeep(columnsInfo[32].columns);
    this.newColumns = columns.filter((item) => item.display == true);
    if (this.newColumns && this.newColumns.length > 10) {
      const a = this.newColumns.length;
      this.scrollx = a * 150;
    } else {
      this.scrollx = 0;
    }

    this.newColumns.map((item) => {
      if (item.key == 'mvalue') {
        item.type = 'number';
        item.toFixed = 2;
      }

      if (item.key == 'enUnitCostPrice' || item.key == 'enUnitNav' || item.key == 'cost') {
        item.type = 'money';
        item.toFixed = 4;
      }

      if (item.key == 'marketValue' || item.key == 'enFloatProfit') {
        item.type = 'money';
      }
      if (item.key == 'investmentType') {
        item.title = (
          <span>
            投资类型
            <Tooltip title='展示的投资类型为同组合同标的的最近一次修改持仓操作'>
              <QuestionCircleOutlined style={{ paddingLeft: '7px' }} />
            </Tooltip>
          </span>
        );
      }

      if (item.key == 'id.dataDt') {
        item.render = (_, record) => {
          const text = record?.id?.dataDt;
          if (text != '--' && text) {
            return `${text.slice(0, 4)}-${text.slice(4, 6)}-${text.slice(6)}`;
          } else {
            return '--';
          }
        };
      }
      if (item.key == 'id.tradingcode') {
        item.render = (_, record) => {
          const text = record?.id?.tradingcode;
          if (text != '--' && text) {
            return text;
          } else {
            return '--';
          }
        };
      }

      if (item.key == 'jysc') {
        item.render = (text, record) => {
          if (record?.id?.exchangecode) {
            const findvalue = config.filter((item) => {
              return item.value == record.id.exchangecode;
            });
            if (findvalue && findvalue.length > 0) {
              return findvalue[0].title;
            } else {
              return '--';
            }
          } else {
            return '--';
          }
        };
      }
      if (item.key == 'id.trdAttr') {
        // 交易属性
        item.render = (_, record) => {
          const val = record?.id?.trdAttr;
          switch (val) {
            case 'PT':
              return '普通';
              break;
            case 'XY':
              return '信用';
              break;
            case 'B':
              return '多头';
              break;
            case 'S':
              return '空头';
              break;
            default:
              return '--';
          }
        };
      }
    });
    return (
      <div>
        <TabC
          type='threeTab'
          tabSource={[
            { title: '证券资产', key: 'pt' },
            { title: '证券负债', key: 'fz' },
          ]}
          activeKey={tabType}
          onChange={(key) => {
            this.setState(
              {
                tabType: key,
              },
              () => {
                this.getTableData();
              },
            );
          }}
          tabBarExtraContent={this.rightButton()}
        />
        <div style={{ marginBottom: '10px' }}>
          {tabType == 'pt' && (
            <div style={{ display: 'flex' }}>
              <div style={{ width: '50%', marginRight: '10px' }}>
                <CollectC
                  dataSource={[
                    {
                      name: '持仓数量', // 名称
                      value: account.amount, // 数值
                    },
                    {
                      name: '资产市值', // 名称
                      value: account.marketValue, // 数值
                      toFixed: 2, // 几位小数
                    },
                    {
                      name: '浮动盈亏', // 名称
                      value: account.enFloatProfit, // 数值
                      toFixed: 2, // 几位小数
                    },
                  ]}
                  type='2'
                  logoName='普通账户'
                  isloading={loading.effects['positionInquiryM/getSearchTotal']}
                />
              </div>
              <div style={{ width: '50%' }}>
                <CollectC
                  dataSource={[
                    {
                      name: '持仓数量', // 名称
                      value: account.amountxy, // 数值
                    },
                    {
                      name: '资产市值', // 名称
                      value: account.marketValuexy, // 数值
                      toFixed: 2, // 几位小数
                    },
                    {
                      name: '浮动盈亏', // 名称
                      value: account.enFloatProfitxy, // 数值
                      toFixed: 2, // 几位小数
                    },
                  ]}
                  type='2'
                  logoName='信用账户'
                  isloading={loading.effects['positionInquiryM/getSearchTotal']}
                />
              </div>
            </div>
          )}
          {tabType == 'fz' && (
            <div>
              <CollectC
                dataSource={[
                  {
                    name: '持仓数量', // 名称
                    value: account.amountfz, // 数值
                  },
                  {
                    name: '资产市值', // 名称
                    value: account.marketValuefz, // 数值
                    toFixed: 2, // 几位小数
                  },
                  {
                    name: '浮动盈亏', // 名称
                    value: account.enFloatProfitfz, // 数值
                    toFixed: 2, // 几位小数
                  },
                ]}
                type='1'
                isloading={loading.effects['positionInquiryM/getSearchTotal']}
              />
            </div>
          )}
        </div>
        <TableC
          columns={this.newColumns || []}
          dataSource={this.state.dataSource || []}
          onChange={this.handleTableChange}
          current={this.state.page}
          pageSize={this.state.pageSize}
          total={this.state.total}
          selfScrollY={true}
          scroll={{ x: this.scrollx }}
          loading={loading.effects['positionInquiryM/etfTable']}
          rowKey={'key'}
        />
      </div>
    );
  }
}
